import { Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import appSdk from '../../utils/app_sdk'
import { GetUserInfo, ToPay, VipData } from '../../api/mine'
import NavBar from '../../components/Navbar'
import './index.less'
import { compareVersions, getAuthentication, getVersion, isIOS } from '../../utils/util'

const appStoreKey = 'appstoreAM'

function VipInfo() {
  const [userInfo, setUserInfo] = useState({ headimgurl: '', nickname: '', wealth_level: 0, glamour_level: 0 })
  const [selectWay, setSelectWay] = useState('aliPay')
  const [selectPrice, setSelectPrice] = useState({})
  const [vipDetail, setVipDetail] = useState({ vipLevel: 0, vip_auth: [], vip_goods: [] })
  const [endTime, setEndTime] = useState('')

  const requestInfo = () => {
    Toast.show({
      title: '加载中...',
      icon: 'loading',
      maskClickable: false
    })
    GetUserInfo().then((res) => {
      setUserInfo(res.data)
    })
    VipData({ system: isIOS ? 2 : 1 })
      .then((res) => {
        console.log(res)
        setVipDetail(res.data)
        setEndTime(res.data.end_time)
        setSelectPrice(res.data.vip_goods[0])
      })
      .finally(() => {
        Toast.clear()
      })
  }

  useEffect(() => {
    requestInfo()
  }, [])

  const [barHeight, setBarHeight] = useState(0)
  const [isAppstore, setIsAppstore] = useState(getAuthentication('packageChannel') === appStoreKey)
  useEffect(() => {
    console.log(
      `%c Version = ${getVersion() || '1.0.0'} 'packageChannel =>', ${getAuthentication('packageChannel')} %c`,
      'background:#41b883 ; padding: 4px; border-radius: 4px;  color: #fff',
      'background:transparent'
    )
    if (compareVersions(getVersion() || '1.0.0', '2.2.0') !== -1) {
      appSdk('setFullScreen', 1)
      if (window?.android && window?.android?.getStatusBarHeight) {
        if (window.android.getStatusBarHeight()) {
          setBarHeight(window.android.getStatusBarHeight() / window.devicePixelRatio)
        }
        console.log('拿到状态栏高度', window.android.getStatusBarHeight(), window.devicePixelRatio)
      } else if (isIOS()) {
        appSdk('getStatusBarHeight', null, (res) => {
          console.log('拿到ios状态栏高度', res, window.devicePixelRatio)
          setBarHeight(res / window.devicePixelRatio)
        })
      }
    }
  }, [])

  const averPrice = (idx, price) => {
    if (idx === 0) return undefined
    if (idx === 1) return `¥${(price / 3).toFixed(3)}/月`
    if (idx === 2) return `¥${(price / 12).toFixed(3)}/月`
  }

  const toPay = () => {
    Toast.show({ icon: 'loading', content: '正在支付中...', maskClickable: false })
    if (!isAppstore) {
      ToPay({ goods_id: selectPrice?.id, type: selectWay === 'aliPay' ? 1 : 2 }).then((res) => {
        console.log('支付信息', res.data)
        appSdk(selectWay, res.data, (result) => {
          console.log('成功回调，拿到的参数是', result)
          requestInfo()
          const data = typeof result === 'string' ? JSON.parse(result) : result
          Toast.show({
            icon: data.status === 'success' ? 'success' : 'fail',
            content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
          })
        })
      })
    } else {
      appSdk(
        'appStorePay',
        {
          id: selectPrice.id,
          good_id: selectPrice.good_id
        },
        (result) => {
          console.log('appstore 成功回调，拿到的参数是', result)
          requestInfo()
          if (typeof result === 'string') {
            const data = JSON.parse(result)
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
          if (typeof result === 'object') {
            const data = result
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
        }
      )
    }
  }

  return (
    <div className="mine_vip_wrap">
      <NavBar
        title="VIP特权"
        style={{
          paddingTop: barHeight
        }}
      />
      <div className="mine_vip_content">
        <div className="new_user_info">
          <div className="nickname">
            <span>Hi {userInfo.nickname}</span>
            <div className="icon"></div>
          </div>
          <p className="vip_status_text">{userInfo.vipLevel > 0 ? `有效期到${endTime}` : '未开通'}</p>
        </div>
        {/* <div className={`mine_vip_card ${userInfo.vipLevel === 0 ? '' : 'isVip'}`}>
          <div className='user_info'>
            <div className='avatar'>
              <img src={userInfo.headimgurl} alt="" />
            </div>
            <div className='name_info'>
              <div className='nickname'>{userInfo.nickname}</div>
              <p className='vip_status_text'>{userInfo.vipLevel === 0 ? '开通贵族即可享受专属权限' : `有效期到${endTime}`}</p>
            </div>
          </div>
        </div> */}
        <div className="vip_content">
          <div className="vip_menu">
            <div className="vip_menu_tit">VIP开通</div>
            <div className="vip_menu_content">
              {vipDetail?.vip_goods.map((item, idx) => (
                <div
                  className={`pay_item ${selectPrice.price === item.price ? 'active' : ''}`}
                  key={item.price}
                  onClick={() => setSelectPrice(item)}
                >
                  <p className="pay_t">{item?.desc}</p>
                  <p className="pay_price">
                    <span>￥</span>
                    {+item?.price || 0}
                  </p>
                  <p className="pay_aver">{averPrice(idx, item.price)}</p>
                </div>
              ))}
            </div>
            {/* <div className='pay_tips'><span>到期按18/每月自动续费</span>，可随时取消</div> */}
          </div>
          <div className="pay_way_wrap" style={{ marginTop: 16 }}>
            <div className="content" style={{ display: isAppstore ? 'none' : '' }}>
              <p>选择支付方式</p>
              <div className="items">
                <div className="pay_item" onClick={() => setSelectWay('wechatPay')}>
                  <div className={`circle ${selectWay === 'wechatPay' ? 'active' : ''}`}></div>
                  {/* <div className="icon wechat"></div> */}
                  <div className="txt">微信支付</div>
                </div>
                <div className="pay_item" onClick={() => setSelectWay('aliPay')}>
                  <div className={`circle ${selectWay === 'aliPay' ? 'active' : ''}`}></div>
                  {/* <div className="icon ali"></div> */}
                  <div className="txt">支付宝</div>
                </div>
              </div>
            </div>
            <div className="pay-tip" style={{ fontSize: '12px', paddingTop: 4, lineHeight: '24px' }}>
              开通会员代表接受
              <span>
                <a href={`${window.baseConfig.baseUrl}/protocol/sla`} style={{ color: '#FFAC30', textDecoration: 'none' }}>
                  《{window.baseConfig.package_name}会员服务协议》
                </a>
              </span>
            </div>
          </div>
          <div className="vip_privilege">
            <div className="privilege_tit">财富特权</div>
            <div className="privileges">
              {vipDetail?.vip_auth?.map((item, idx) => (
                <div className={`privilege_item`}>
                  <div className="privilege_item_icon">
                    <img src={item.img} alt="" />
                  </div>
                  <div className="privilege_item_t">{item.title}</div>
                  <div className="privilege_item_text">
                    {item.desc_line_1}
                    <br />
                    {item.desc_line_2}
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="pay_button" onClick={toPay}>
            <p>{`¥${selectPrice.price} 立刻开通`}</p>
          </div>
          {/* <div className='pay_info'>
            <div className='econ_money'>已省 <span>¥ 0</span></div>
            <div className="pay_btn_cotent">
              <div className="pay_btn" onClick={toPay}>
                ¥<span>{selectPrice?.price || 0}</span>立即{userInfo.vipLevel === 0 ? '开通' : '续费'}
              </div>
              <br />
              <div className='pay-tip'>开通会员代表接受<span><a href='https://www.aimengtec.com//protocol/sla' style={{ color: '#AFFBA1', textDecoration: 'none' }}>《{window.baseConfig.package_name}会员服务协议》</a></span></div>
            </div>
          </div> */}
        </div>
      </div>
    </div>
  )
}

export default VipInfo
